package com.jiangnan.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jiangnan.entity.PaymentLog
import com.jiangnan.entity.Res
import com.jiangnan.repository.PaymentRepository
import kotlinx.coroutines.launch

class TransactionViewModel : ViewModel() {
  private val repo = PaymentRepository()

  private val _logs = MutableLiveData<List<PaymentLog>>()
  val logs: LiveData<List<PaymentLog>> = _logs

  private val _error = MutableLiveData<String>()
  val error: LiveData<String> = _error

  private val _toastMessage = MutableLiveData<String>()
  val toastMessage: LiveData<String> = _toastMessage

  fun loadLogs(userId: Long) {
    viewModelScope.launch {
      try {
        val res: Res<List<PaymentLog>> = repo.getLogs(userId)
        if (res.code == 1 && res.data != null) {
          _logs.value = res.data!!
          _toastMessage.value = "加载成功"
        } else {
          _error.value = res.msg
        }
      } catch (e: Exception) {
        _error.value = e.message
        e.printStackTrace()
      }
    }
  }
}